// Set variables
$(document).ready(function () {

	function imageOnload(base64_str, filename){

		let canvas = document.createElement("canvas");
		canvas.width = this.width / 2;//image.width / 4;//1604;// image.width;// 1350;
		canvas.height = this.height;
		let context = canvas.getContext("2d");
		//-(image.width / 4)
		context.drawImage(this, -(this.width / 2), 0, this.width, this.height); //image.width, image.height); , image.width, image.height

		let img_right = canvas.toDataURL("image/png"); //得到图片的base64编码数据

		downloadFile( filename + '_1.png', img_right);

		// 将文件在一个 window 窗口中打开，并隐藏这个窗口。

		// var win = window.open("", "_blank");
		// win.document.write('<html><head><title>渲染图</title></head><body><div style=\'text-align:center\'><img src="' + img_right + '" /></div></body></html>');

		context.clearRect(0, 0, canvas.width, canvas.height);
		context.drawImage(this, 0, 0, this.width, this.height); //image.width, image.height); , image.width, image.height

		let img_left = canvas.toDataURL("image/png"); //得到图片的base64编码数据
		// var win = window.open().document.write('<html><head><title>渲染图</title></head><body><div style=\'text-align:center\'><img src="' + img_left + '" /></div></body></html>');

		downloadFile( filename + '_2.png', img_left);
	}

	function base64ToBlob(code) {
		let parts = code.split(';base64,');
		let contentType = parts[0].split(':')[1];
		let raw = window.atob(parts[1]);
		let rawLength = raw.length;

		let uInt8Array = new Uint8Array(rawLength);

		for (let i = 0; i < rawLength; ++i) {
			uInt8Array[i] = raw.charCodeAt(i);
		}
		return new Blob([uInt8Array], { type: contentType });
	}

	function downloadFile(fileName, content) {
		let aLink = document.createElement('a');
		
		let blob = base64ToBlob(content); //new Blob([content]);

		let evt = document.createEvent("HTMLEvents");
		evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
		aLink.download = fileName;
		aLink.href = URL.createObjectURL(blob);

		// aLink.dispatchEvent(evt);
		aLink.click();
	}
	//base64转blob

	let pageSet = new Set();
	// 重写按键限制
	document.onkeydown = undefined; // 注意这里的document

	document.querySelector('html').addEventListener('keydown', function keydown(e) {
		e.stopImmediatePropagation();
	})

	//document.querySelector('#view')();// width:1604px; transform:translated(-308px,0px,0px)

	chrome.extension.sendMessage({ name: "getIP" }, function (response) {

		chrome.extension.sendMessage({ name: "getOptions" }, function (response) {

			// 重写按键限制
			document.onkeydown = undefined; // 注意这里的document

			var websiteIP_status = response.EnableRenderImg;
			if (websiteIP_status == "Disable" || typeof websiteIP_status == 'undefined') {


				$("body").append('<div id="rendFloatDom" class="NYwishes" style="z-index:99999">'
					+ '<div id="expandInputBtn" class="send"><div class="send-btn" style="float:right"><a onclick="document.getElementById(\'expandInputBtn\').style.display=\'none\';document.getElementById(\'showRenderImgDiv\').style.display=\'block\';">展开</a></div></div>'
					+ '<div class="send" id="showRenderImgDiv" style="display:none">'
					+ '<div class="send-btn" ><a id="RenderImgBtn">渲染</a></div></div></div>'
					+ '');

				function doRender() {

					var script = document.createElement('script');
					script.type = 'text/javascript';
					script.innerHTML = "document.body.setAttribute('data-fp0', img_obj[0].toDataURL(\"image/png\"));" +
						"document.body.setAttribute('data-fp1', img_obj[1].toDataURL(\"image/png\"));" +
						"document.body.setAttribute('data-fp2', img_obj[2].toDataURL(\"image/png\"));";
					document.head.appendChild(script);
					document.head.removeChild(script);

					base64_0 = document.body.getAttribute('data-fp0');
					base64_1 = document.body.getAttribute('data-fp1');
					base64_2 = document.body.getAttribute('data-fp2');

					if (pageSet.has(base64_0.slice(0, 100)) == false) {
						let image = new Image();
						// 解决跨域 Canvas 污染问题

						pageSet.add(base64_0.slice(0, 100));
						image.setAttribute("crossOrigin", "anonymous");
						image.onload = imageOnload(base64_0, pageSet.size);
						
						// function () {

						// 	let canvas = document.createElement("canvas");
						// 	canvas.width = image.width / 2;//image.width / 4;//1604;// image.width;// 1350;
						// 	canvas.height = image.height;
						// 	let context = canvas.getContext("2d");
						// 	//-(image.width / 4)
						// 	context.drawImage(image, -(image.width / 2), 0, image.width, image.height); //image.width, image.height); , image.width, image.height

						// 	let img_right = canvas.toDataURL("image/png"); //得到图片的base64编码数据

						// 	downloadFile( pageSet.size + '_1.png', img_right);

						// 	// 将文件在一个 window 窗口中打开，并隐藏这个窗口。

						// 	// var win = window.open("", "_blank");
						// 	// win.document.write('<html><head><title>渲染图</title></head><body><div style=\'text-align:center\'><img src="' + img_right + '" /></div></body></html>');

						// 	context.clearRect(0, 0, canvas.width, canvas.height);
						// 	context.drawImage(image, 0, 0, image.width, image.height); //image.width, image.height); , image.width, image.height

						// 	let img_left = canvas.toDataURL("image/png"); //得到图片的base64编码数据
						// 	// var win = window.open().document.write('<html><head><title>渲染图</title></head><body><div style=\'text-align:center\'><img src="' + img_left + '" /></div></body></html>');

						// 	downloadFile( pageSet.size + '_2.png', img_left);


						// };
						image.src = base64_0;//
		
					}

					if (pageSet.has(base64_1.slice(0, 100)) == false) {
						let image1 = new Image();
						// 解决跨域 Canvas 污染问题
						image1.setAttribute("crossOrigin", "anonymous");
						image1.onload = function () {
							
							pageSet.add(base64_1.slice(0, 100));

							let canvas = document.createElement("canvas");
							canvas.width = image1.width / 2;//image.width / 4;//1604;// image.width;// 1350;
							canvas.height = image1.height;
							let context = canvas.getContext("2d");
							//-(image.width / 4)
							context.drawImage(image1, -(image1.width / 2), 0, image1.width, image1.height); //image.width, image.height); , image.width, image.height

							let img_right = canvas.toDataURL("image/png"); //得到图片的base64编码数据

							downloadFile( pageSet.size + '_1.png', img_right);

							// 将文件在一个 window 窗口中打开，并隐藏这个窗口。

							// var win = window.open("", "_blank");
							// win.document.write('<html><head><title>渲染图</title></head><body><div style=\'text-align:center\'><img src="' + img_right + '" /></div></body></html>');

							context.clearRect(0, 0, canvas.width, canvas.height);
							context.drawImage(image1, 0, 0, image1.width, image1.height); //image.width, image.height); , image.width, image.height

							let img_left = canvas.toDataURL("image/png"); //得到图片的base64编码数据
							// var win = window.open().document.write('<html><head><title>渲染图</title></head><body><div style=\'text-align:center\'><img src="' + img_left + '" /></div></body></html>');

							downloadFile( pageSet.size + '_2.png', img_left);

						};
						image1.src = base64_1;

					}

					if (pageSet.has(base64_2.slice(0, 100)) == false) {
						let image2 = new Image();
						// 解决跨域 Canvas 污染问题
						image2.setAttribute("crossOrigin", "anonymous");
						image2.onload = function () {

							pageSet.add(base64_2.slice(0, 100));

							let canvas = document.createElement("canvas");
							canvas.width = image2.width / 2;//image.width / 4;//1604;// image.width;// 1350;
							canvas.height = image2.height;
							let context = canvas.getContext("2d");
							//-(image.width / 4)
							context.drawImage(image2, -(image2.width / 2), 0, image2.width, image2.height); //image.width, image.height); , image.width, image.height

							let img_right = canvas.toDataURL("image/png"); //得到图片的base64编码数据

							downloadFile( pageSet.size + '_1.png', img_right);

							// 将文件在一个 window 窗口中打开，并隐藏这个窗口。

							// var win = window.open("", "_blank");
							// win.document.write('<html><head><title>渲染图</title></head><body><div style=\'text-align:center\'><img src="' + img_right + '" /></div></body></html>');

							context.clearRect(0, 0, canvas.width, canvas.height);
							context.drawImage(image2, 0, 0, image2.width, image2.height); //image.width, image.height); , image.width, image.height

							let img_left = canvas.toDataURL("image/png"); //得到图片的base64编码数据
							// var win = window.open().document.write('<html><head><title>渲染图</title></head><body><div style=\'text-align:center\'><img src="' + img_left + '" /></div></body></html>');

							downloadFile( pageSet.size + '_2.png', img_left);

						};
						image2.src = base64_2;

					}

				}

				$("#choose-id").keydown(function (e) {
					if (e.keyCode == 13) {
						doRender();
					}
				});

				$('#RenderImgBtn').click(function () {
					doRender();
				});
			}
		});
	});
});
